<template>
  <div>
    <h3>用户列表
      <router-link to="/user/add" class="btn btn-warning">添加用户</router-link>
    </h3>
    <div class="alert alert-success" v-show="success_show" style="width: 20%" role="alert">
      {{msg}}
    </div>
    <div class="alert alert-danger" v-show="failed_show" style="width: 20%" role="alert">
      {{msg}}
    </div>
    <!--路由视图-->
    <router-view/>
    <table class="table table-dark table-striped">
      <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>性别</th>
        <th>年龄</th>
        <th>操作</th>
      </tr>
      <tr v-for="(user,index) in userList" :key="index">
        <td>{{user.id}}</td>
        <td>{{user.name}}</td>
        <td>{{user.gender}}</td>
        <td>{{user.age}}</td>
        <td>
          <a :href="'#/user/edit/'+user.id" class="btn btn-primary">修改</a>
          <button type="button" @click="deleteById(user.id)" class="btn btn-danger">删除</button>
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
  export default {
    name: "User",
    data() {
      return ({
        userList: [],
        msg:'',
        success_show:false,
        failed_show:false
      });
    },
    methods: {
      findAll() {
        this.$http.get(this.$api + '/user/findAll').then((response) => {
          this.userList = response.data
        });
      },
      deleteById(id){
        this.success_show = false;
        this.failed_show = false;
        this.$http.delete(this.$api + '/user/'+id).then((response)=>{
          this.msg = response.data.msg;
          if (response.data.success){
            this.success_show = true;
          }else {
            this.failed_show = true;
          }
          this.findAll();
        });
      }
    },
    components: {},
    created() {
      this.findAll();
    },
    watch: {//监听路由的变化，用于及时更新最新的数据
      $route: {
        //参数1:监听到的变化后的路由，参数2:旧的路由
        handler: function (newRoute){//这里不要用箭头函数，如果使用箭头函数的话this为undefined
          if (newRoute.path === '/user') {
            this.findAll();
          }
        },
        deep: true
      }
    }
  }
</script>

<style scoped>

</style>